<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>角色管理</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="../../layuimini/lib/layui-v2.5.5/css/layui.css" media="all" />
  <link rel="stylesheet" href="../../layuimini/css/public.css" media="all" />
</head>

<body>
  <div class="layuimini-container">
    <div class="layuimini-main">
      <fieldset class="table-search-fieldset">
        <legend>搜索信息</legend>
        <div style="margin: 10px 10px 10px 10px">
          <form class="layui-form layui-form-pane" action="">
            <div class="layui-form-item">
              <label class="layui-form-label">角色名称:</label>
              <div class="layui-input-inline">
                <input id="role_name_id" name="name" placeholder="请输入角色名称" class="layui-input" />
              </div>

              <label class="layui-form-label">角色描述:</label>
              <div class="layui-input-inline">
                <input id="role_desc_id" name="description" placeholder="请输入角色描述" class="layui-input" />
              </div>

              <div class="layui-inline">
                <button type="submit" class="layui-btn" lay-submit lay-filter="data-search-btn">
                  <i class="layui-icon layui-icon-search"></i> 搜 索
                </button>

                <button type="button" class="layui-btn layui-btn-primary" id="data-reset-btn">
                  <i class="layui-icon"></i> 重 置
                </button>
              </div>
            </div>
          </form>
        </div>
      </fieldset>

      <script type="text/html" id="toolbarDemo">
          <div class="layui-btn-group">
            <button
              class="layui-btn layui-btn layui-btn-sm data-add-btn"
              lay-event="add"
            >
              添加
            </button>
            <button
              class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn"
              lay-event="delete"
            >
              删除
            </button>
            <button
              class="layui-btn layui-btn-sm layui-btn-warm"
              lay-event="refresh"
            >
              刷新
            </button>
            <button
              class="layui-btn layui-btn-sm layui-btn-normal"
              lay-event="export"
            >
              导出全部数据
            </button>
          </div>
        </script>

      <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

      <script type="text/html" id="currentTableBar">
          <div
            class="layui-btn layui-btn layui-btn-xs data-count-edit"
            lay-event="role_menu"
          >
            菜单授权
          </div>
          <div
            class="layui-btn layui-btn-normal layui-btn-xs data-count-edit"
            lay-event="edit"
          >
            编辑
          </div>
          <div
            class="layui-btn layui-btn-xs layui-btn-danger data-count-delete"
            lay-event="delete"
          >
            删除
          </div>
        </script>
    </div>
  </div>

  <!-- 新增编辑角色 -->
  <script type="text/html" id="roleEditDialog">
      <form
        id="roleEditForm"
        lay-filter="roleEditForm"
        class="layui-form "
        style="padding-left:20px;margin-top: 20px; padding-right: 50px;">

        <input name="roleId" type="hidden" />
        <div class="layui-form layuimini-form">
          <input name="id" type="hidden" />

          <div class="layui-form-item">
              <label class="layui-form-label required">角色名称:</label>
              <div class="layui-input-block">
                <input
                  name="roleName"
                  placeholder="请输入角色名称"
                  class="layui-input"
                  lay-verify="required"
                  lay-verType="tips"
                />
              </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label required">角色描述:</label>
            <div class="layui-input-block">
              <textarea id="desc" 
                name="roleDescription" 
                placeholder="请输入角色描述" 
                class="layui-textarea"
                lay-verType="tips"
                lay-verify="required"
                >
              </textarea>

            </div>
          </div>

            <div class="layui-form-item ">
              <label class="layui-form-label"></label>
              <button class="layui-btn layui-btn-normal" lay-filter="roleEditSubmit" lay-submit>
                提交
              </button>
              <button
                class="layui-btn layui-btn-primary"
                type="button"
                ew-event="closeDialog"
                id="Cancel"
              >
                取消
              </button>
          </div>


          </div>
        </div>

      </form>
    </script>

  <!-- 角色分配菜单 -->
  <script type="text/html" id="roleMenuDialog">
      <div class="layuimini-container">
        <div class="layuimini-main">
          <div class="layui-form ">
            <div class="layui-form-item">
              <label class="layui-form-label">角色名称:</label>
              <div class="layui-input-inline">
                <input id="role_name" class="layui-input" disabled />
              </div>

              <label class="layui-form-label">角色描述:</label>
              <div class="layui-input-inline">
                <input id="role_desc" class="layui-input" disabled />
              </div>
            </div>

            <!-- 菜单树 -->
            <div class="layui-form-item">
              <label class="layui-form-label">选择菜单:</label>
              <div class="layui-input-inline" id="roleMenuTree"></div>
            </div>
          </div>
        </div>
      </div>
    </script>

  <script src="../../layuimini/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
  <script src="../../layuimini/js/lay-config.js" charset="utf-8"></script>

  <script>
    layui.use(
      [
        "layer",
        "form",
        "table",
        "laydate",
        "upload",
        "common",
        "excel",
        "transfer",
        "tree",
      ],
      function () {
        var $ = layui.jquery,
          form = layui.form,
          laydate = layui.laydate,
          table = layui.table,
          upload = layui.upload,
          common = layui.common,
          excel = layui.excel,
          transfer = layui.transfer,
          tree = layui.tree;

        tableIns = table.render({
          elem: "#currentTableId",
          url: common.api + "/role/paged-list",
          where: { token: common.getToken },
          toolbar: "#toolbarDemo",
          title: "角色信息",
          limits: [1, 5, 10, 15, 20],
          limit: 10,
          page: true,
          skin: "row",
          even: true,
          cols: [
            [
              {
                type: "checkbox",
                width: 50,
              },
              {
                field: "roleId",
                title: "角色ID",
                width: 100,
                sort: true,
                align: "center",
              },
              {
                field: "roleName",
                // width: 100,
                title: "角色名称",
                align: "center",
                sort: true,
              },
              {
                field: "roleDescription",
                // width: 120,
                title: "角色描述",
                align: "center",
                sort: true,
              },

              {
                title: "操作",
                width: 220,
                toolbar: "#currentTableBar",
                align: "center",
              },
            ],
          ],
          parseData: function (res) {
            if (res.code != 200) {
              common.login();
            }
            return {
              code: res.code, //解析接口状态
              msg: res.msg, //解析提示文本
              count: res.data.total, //解析数据长度
              data: res.data.list, //解析数据列表
            };
          },
          response: {
            statusCode: 200, //重新规定成功的状态码为 200，table 组件默认为 0
          },
          request: {
            pageName: "page", //页码的参数名称，默认：page
            limitName: "size", //每页数据量的参数名，默认：limit
          },
          initSort: {
            field: "roleId",
            type: "asc",
          },
        });

        //监听工具栏添加删除刷新
        table.on("toolbar(currentTableFilter)", function (obj) {
          if (obj.event === "add") {
            // 监听添加操作
            showEditModel();
            $("#desc").val("");
          } else if (obj.event === "delete") {
            // 监听删除操作
            var data = table.checkStatus("currentTableId").data;
            if (data.length === 0) {
              layer.msg("请选择要删除的数据", { icon: 2 });
              return;
            }
            var ids = data.map(function (d) {
              return d.roleId;
            });
            doDel(ids);
          } else if (obj.event === "refresh") {
            tableIns.reload({
              url: common.api + "/role/paged-list",
              // where: {},
            });
          } else if (obj.event === "export") {
            // 导出
            common.ajax(common.api + "/role/list", null, function (res) {
              var data = res.data;

              data = common.compare(data);
              data = excel.filterExportData(data, [
                "roleId",
                "roleName",
                "roleDescription",
              ]);
              data.unshift({
                roleId: "角色ID",
                roleName: "角色名称",
                roleDescription: "角色描述"
              });
              var timestart = Date.now();
              excel.exportExcel(
                {
                  sheet1: data,
                },
                "角色列表.xlsx",
                "xlsx"
              );
              var timeend = Date.now();

              var spent = (timeend - timestart) / 1000;
              layer.msg("导出成功", { icon: 1 });
            });
          }
        });

        //监听编辑删除
        table.on("tool(currentTableFilter)", function (obj) {
          if (obj.event === "edit") {
            showEditModel(obj.data);
          } else if (obj.event === "delete") {
            doDel([obj.data.roleId]);
          } else if (obj.event === "role_menu") {
            showRoleMenuDialog(obj.data);
          }
        });

        function getRoleMenu(roleId) {
          var data = [];
          $.ajax({
            url: common.api + "/role/" + roleId + "/menuList",
            type: "get",
            headers: { authorization: common.getToken("token") },
            async: false,
            success: function (result) {
              // 设置节点默认展开
              if (result && result.length > 0) {
                for (let k = 0; k < result.length; k++) {
                  const e = result[k];
                  e.spread = true;
                  data.push(e);
                }
              }
            },
          });
          return data;
        }

        //递归获取所有选中节点（包含子节点)
        function getCheckedId(jsonObj) {
          var id = "";
          $.each(jsonObj, function (index, item) {
            if (id != "") {
              id = id + "," + item.id;
            } else {
              id = item.id;
            }
            var i = getCheckedId(item.children);
            if (i != "") {
              id = id + "," + i;
            }
          });
          return id;
        }

        // 角色分配菜单
        function showRoleMenuDialog(val) {
          var idx = layer.open({
            type: 1,
            area: ["710px", "400px"],
            title: "菜单授权",
            // offset:'100px',
            anim: 1,
            shade: 0.6,
            content: $("#roleMenuDialog").html(),
            btn: ["提交", "取消"],

            btn1: function (index, layero, that) {
              // 提交
              var selectMenus = tree.getChecked("role_menu_id");
              var str = getCheckedId(selectMenus);
              var menuIds = [];
              if (str) {
                menuIds = menuIds.concat(str.split(","));
              }

              var roleMenuForm = {};
              roleMenuForm.roleId = val.roleId;
              roleMenuForm.menuIds = menuIds;
              common.ajax(
                common.api + "/role/saveMenus",
                JSON.stringify(roleMenuForm),
                function (res) {
                  if (res.code === 200) {
                    layer.close(index);
                    layer.msg(res.msg, { icon: 1 });
                    setTimeout(() => {
                      table.reload("currentTableId");
                    }, 1000);
                  } else {
                    layer.msg(res.msg, { icon: 2 });
                  }
                },
                "post",
                function (data) {
                  layer.msg(data.msg, { icon: 2 });
                },
                false,
                true
              );
            },
            btn2: function (index, layero, that) {
              // 取消
              // return true;
            },

            success: function (layero, dIndex) {
              $("#role_name").val(val.roleName);
              $("#role_desc").val(val.roleDescription);

              tree.render({
                elem: "#roleMenuTree",
                data: getRoleMenu(val.roleId),
                showLine: true,
                showCheckbox: true,
                onlyIconControl: false, // 是否仅允许节点左侧图标控制展开收缩
                autoCheckedChild: false, // 选中父节点是否自动选择子节点，false-不选中
                id: "role_menu_id",
              });

              $("#Cancel").click(function () {
                layer.close(idx);
              });
            },
          });
        }

        function showEditModel(formData) {
          var idx = layer.open({
            type: 1,
            area: ["500px", "300px"],
            title: formData ? "编辑" : "添加",

            anim: 1,
            shade: 0.6,
            content: $("#roleEditDialog").html(),
            success: function (layero, dIndex) {
              // 回显表单数据
              form.val("roleEditForm", formData);

              // 表单提交事件
              form.on("submit(roleEditSubmit)", function (data) {
                common.ajax(
                  formData
                    ? common.api + "/role/update"
                    : common.api + "/role/add",
                  JSON.stringify(data.field),
                  function (res) {
                    if (res.code === 200) {
                      layer.close(dIndex);
                      layer.msg(res.msg, { icon: 1 });
                      setTimeout(() => {
                        table.reload("currentTableId");
                      }, 1000);
                    } else {
                      layer.msg(res.msg, { icon: 2 });
                    }
                  },
                  formData ? "put" : "post",
                  function (data) {
                    layer.msg(data.msg, { icon: 2 });
                  },
                  false,
                  true
                );
                return false;
              });

              $("#Cancel").click(function () {
                layer.close(idx);
              });
            },
          });
        }

        function doDel(ids) {
          layer.confirm(
            "确定要删除选中数据吗？",
            {
              skin: "layui-layer-admin",
              shade: 0.1,
            },
            function (i) {
              common.ajax(
                common.api + "/role/delete",
                JSON.stringify(ids),
                function (res) {
                  if (res.code === 200) {
                    layer.msg(res.msg, { icon: 1 });
                    tableIns.reload();
                  } else {
                    layer.msg(res.msg, { icon: 2 });
                  }
                },
                "DELETE",
                function (data) {
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                  return;
                }
              );
              layer.close(i);
            }
          );
        }

        // 监听搜索操作
        form.on("submit(data-search-btn)", function (data) {
          var param = data.field;
          // return false
          // 执行搜索重载
          tableIns.reload({
            url: common.api + "/role/paged-list",
            method: "get",
            where: param,
          });
          return false;
        });
        // 监听重置操作
        $("#data-reset-btn").click(function () {
          $("#role_name_id").val("");
          $("#role_desc_id").val("");
          tableIns.reload({
            url: common.api + "/role/paged-list",
            method: "get",
            where: { name: "", description: "" },
          });
        });

        layer.ready(function () { });
      }
    );
  </script>
</body>

</html>